package com.cy.pj.goods.pojo.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository//描述具体实现对象，交给spring管理
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() throws Exception {
        /*1.获取jdbc连接
           2.创建statement对象，基于对象发送SQL
           3.发送SQL，执行查询
           4.处理结果集
           5.释放资源
         */
        Connection conn = dataSource.getConnection();
        Statement sta = conn.createStatement();
        String sql = "select * from tb_goods";
        ResultSet rs = sta.executeQuery(sql);
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("name", rs.getString("name"));
                map.put("remark", rs.getString("remark"));
                map.put("createdTime", rs.getTimestamp("createdTime"));
                list.add(map);
            }
            return list;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        finally {
            if (rs != null) try { rs.close(); } catch (Exception e) { e.printStackTrace(); }
            if (sta != null) try { sta.close(); } catch (Exception e) { e.printStackTrace(); }
            //这里的连接是返回到了池中
            if (conn != null) try { conn.close(); } catch (Exception e) { e.printStackTrace(); }
        }
    }
}





















